package com.example.test_witns.ui.contacts;

import static android.content.ContentValues.TAG;
import static com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.test_witns.ChatActivity;
import com.example.test_witns.R;
import com.example.test_witns.adapter.friends.FriendsAdapter;
import com.example.test_witns.databinding.FragmentContactsBinding;
import com.example.test_witns.pojo.Contacts_info;
import com.example.test_witns.ui.add_friends.AddFriendsActivity;
import com.example.test_witns.utils.FriendsDatabaseHelper;
import com.example.test_witns.utils.MyInfosHelper;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMConversationListFilter;
import com.tencent.imsdk.v2.V2TIMConversationListener;
import com.tencent.imsdk.v2.V2TIMFriendInfo;
import com.tencent.imsdk.v2.V2TIMFriendshipManager;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMValueCallback;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ContactsFragment extends Fragment {

    private FragmentContactsBinding binding;
    private RecyclerView friendRecycler;
    private FriendsAdapter friendsAdapter;
    private NavController navController;
    private List<Contacts_info> contactsInfosList;
    private byte[] avatarBytes;
    private String avatar_URL;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        ContactsViewModel contactsViewModel =
                new ViewModelProvider(this).get(ContactsViewModel.class);

        binding = FragmentContactsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        Window window = getActivity().getWindow();
        window.setStatusBarColor(Color.parseColor("#eeeeee"));

        MyInfosHelper myInfosHelper = new MyInfosHelper(getContext());

        friendRecycler = root.findViewById(R.id.contacts_RecyclerView);
        friendRecycler.setLayoutManager(new LinearLayoutManager(root.getContext()));

        contactsInfosList = new ArrayList<>();
        friendsAdapter = new FriendsAdapter(contactsInfosList);
        friendsAdapter.setOnFriendsClickListener(new FriendsAdapter.OnFriendsClickListener() {
            @Override
            public void onFriendClicked(byte[] targetAvatar, String targetUserId, String targetNickname) {
                Context context1 = getContext();
                Intent ChatNavigationView = new Intent(context1, ChatActivity.class);
                ChatNavigationView.putExtra("targetUserId",targetUserId);
                ChatNavigationView.putExtra("targetNickname", targetNickname);
                ChatNavigationView.putExtra("targetAvatar", targetAvatar);
                V2TIMManager.getMessageManager().markC2CMessageAsRead(targetUserId, new V2TIMCallback() {
                    @Override
                    public void onSuccess() {
                        Log.d(TAG, "onSuccess:" + "清除完成");
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });

                startActivity(ChatNavigationView);
            }
        });
        friendRecycler.setAdapter(friendsAdapter);

        SwipeRefreshLayout swipeRefreshLayout = root.findViewById(R.id.swipeRefreshLayout_contacts);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (myInfosHelper.checkIfLogin()){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    swipeRefreshLayout.setRefreshing(false); // 刷新完成后关闭刷新动画
                                    showToastAboveView(friendRecycler, getContext(), "好友列表刷新成功");
                                    friendsAdapter.removeAllFriends();
                                    getAndLoadFriendList();
                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showToastAboveViewProhibitedStyle(friendRecycler, getContext(), "请登录后查看好友列表");
                                    swipeRefreshLayout.setRefreshing(false);
                                }
                            });
                        }
                    }
                }).start();
            }
        });

        V2TIMManager.getConversationManager().addConversationListener(new V2TIMConversationListener() {
            @Override
            public void onConversationChanged(List<V2TIMConversation> list) {
                // 会话信息发生变化
                for (V2TIMConversation conversation : list) {
                    // 检查是否是C2C会话
                    if (conversation.getType() == V2TIMConversation.V2TIM_C2C) {
                        // 获取用户ID
                        String userID = conversation.getUserID();
                        for (Contacts_info info : contactsInfosList) {
                            if (info.getUserId().equals(userID)) {
                                // 更新未读消息数
                                info.setUnreadCount(conversation.getUnreadCount());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 通知Adapter数据变化
                                        int position = contactsInfosList.indexOf(info);
                                        if (position != -1) {
                                            friendsAdapter.notifyItemChanged(position);
                                        }
                                    }
                                });
                                break;
                            }
                        }
                    }
                }
            }
        });

        FriendsDatabaseHelper friendsDatabaseHelper = new FriendsDatabaseHelper(this.getContext());
        friendsDatabaseHelper.loadFriends(new FriendsDatabaseHelper.FriendsLoadedListener() {
            @Override
            public void onFriendLoaded(int id, String name, byte[] avatar, String lastMessage, String lastContact) {
                //更新UI
//                addFriendsToList(name, lastMessage, lastContact);
            }
        });

        if (myInfosHelper.checkIfLogin()) getAndLoadFriendList();

        navController = NavHostFragment.findNavController(this);
        View add_new_friend = root.findViewById(R.id.add_new_friend);
        add_new_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myInfosHelper.checkIfLogin()){
                    Context context = getContext();
                    Intent intent = new Intent(context, AddFriendsActivity.class);
                    startActivity(intent);
                }else {
                    showToastAboveViewProhibitedStyle(friendRecycler, getContext(), "登录后方可添加好友");
                }
            }
        });

        return root;
    }

    private void getAndLoadFriendList() {
        V2TIMManager.getFriendshipManager().getFriendList(new V2TIMValueCallback<List<V2TIMFriendInfo>>() {
            @Override
            public void onSuccess(List<V2TIMFriendInfo> v2TIMFriendInfos) {
                v2TIMFriendInfos.forEach(v2TIMFriendInfo -> {
                    String userID = v2TIMFriendInfo.getUserID();
                    long friendAddTime = v2TIMFriendInfo.getFriendAddTime();
                    String friendRemark = v2TIMFriendInfo.getFriendRemark();
                    String URL = v2TIMFriendInfo.getUserProfile().getFaceUrl();
                    String ID = userID;
                    String remark = v2TIMFriendInfo.getUserProfile().getNickName();

                    V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
                        @Override
                        public void onSuccess(Long aLong) {
                            Log.d(TAG, "getTotalUnreadMessageCount:" + aLong);
                        }

                        @Override
                        public void onError(int i, String s) {

                        }
                    });

                    V2TIMConversationListFilter filter = new V2TIMConversationListFilter();
                    filter.setConversationType(V2TIMConversation.V2TIM_C2C);

                    V2TIMManager.getConversationManager().getUnreadMessageCountByFilter(filter, new V2TIMValueCallback<Long>() {
                        @Override
                        public void onSuccess(Long aLong) {
                            Log.d(TAG, "getUnreadMessageCountByFilter:" + aLong);
                        }

                        @Override
                        public void onError(int i, String s) {

                        }
                    });

                    V2TIMManager.getConversationManager().getConversation("c2c_" + ID, new V2TIMValueCallback<V2TIMConversation>() {
                        /**
                         */
                        @Override
                        public void onSuccess(V2TIMConversation v2TIMConversation) {
                            long unreadCount = v2TIMConversation.getUnreadCount();
                            addFriendsToList(remark, userID, friendRemark, String.valueOf(friendAddTime), unreadCount, URL);
                        }

                        /**
                         * @param i
                         * @param s
                         */
                        @Override
                        public void onError(int i, String s) {

                        }
                    });
                });
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }

    public void addFriendsToList(String remark, String userID, String lastMessage, String lastContact, long unreadCount, String URL){
        String senderID = userID;
        String last_message = lastMessage;
        String last_contact = lastContact;

        V2TIMFriendshipManager friendshipManager = V2TIMManager.getFriendshipManager();
        List<String> userIDList = new ArrayList<>();
        userIDList.add(userID);

        Contacts_info contactsInfo = new Contacts_info(
                userID, remark, 0, null, null, last_message, last_contact, unreadCount, URL);

        friendsAdapter.addFriend(contactsInfo);
    }

    public void showToastAboveView(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_confirm_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight + 30; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

    public void showToastAboveViewProhibitedStyle(View view, Context context, String message) {
        // 创建Toast
        View customView = LayoutInflater.from(context).inflate(R.layout.custom_toast_prohibited_layout, null);
        TextView toastText = customView.findViewById(R.id.toast_message);
        toastText.setText(message);

        Toast toast = new Toast(context);
        toast.setView(customView);
        toast.setDuration(Toast.LENGTH_SHORT);

        // 获取控件的位置（相对于屏幕）
        int[] location = new int[2];
        view.getLocationOnScreen(location); // 获取控件在屏幕上的位置
        int viewX = location[0]; // 控件的X坐标
        int viewY = location[1]; // 控件的Y坐标

        WindowInsets insets = getActivity().getWindow().getDecorView().getRootWindowInsets();
        int cutoutHeight = 0;
        if (insets != null) {
            cutoutHeight = insets.getSystemWindowInsetTop(); // 获取刘海高度
        }

        // 计算Toast的偏移量
        int xOffset = 0; // 水平偏移量，与控件的X坐标对齐
        int yOffset = viewY - cutoutHeight + 30; // 垂直偏移量，让Toast显示在控件的顶部

        // 设置Toast的位置
        toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, xOffset, yOffset);

        // 显示Toast
        toast.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public byte[] downloadAvatar(String avatarUrl) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(avatarUrl)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().bytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}